import React, { useRef, useEffect, useState } from 'react'
import { View, Text, ScrollView, Image } from '@tarojs/components'
import Taro, { getCurrentInstance, useDidShow } from '@tarojs/taro'
import { useSelector, useDispatch } from 'react-redux'
import { useImmer } from 'use-immer'
import { AtTabs, AtTabsPane } from 'taro-ui'
import {
  SpFilterBar,
  SpTagBar,
  SpGoodsItem,
  SpSearchBar,
  SpPage,
  SpScrollView,
  SpPrice
} from '@/components'
import { fetchUserFavs } from '@/store/slices/user'
import doc from '@/doc'
import api from '@/api'
import { pickBy, classNames, getDistributorId, entryLaunch, VERSION_STANDARD } from '@/utils'
import S from '@/spx'
import qs from 'qs'

import './list.scss'

const initialState = {
  leftList: [],
  rightList: [],
  brandList: [],
  brandSelect: [],
  filterList: [
    { title: '综合' },
    { title: '销量' },
    { title: '价格', icon: 'icon-shengxu-01' },
    { title: '价格', icon: 'icon-jiangxu-01' }
  ],
  curFilterIdx: 0,
  tagList: [],
  curTagIdx: 0,
  keywords: '',
  show: false,
  fixTop: 0,
  routerParams: null,
  card_id: null, // 兑换券
  tabsList: [
    {
      title: '商品'
    }
  ],
  curTabsIdx: 0,
  storeBase: {
    backgroundColor: '#fff',
    imgUrl: '',
    padded: true,
    subtitle: '',
    title: ''
  },
  storeData: [],
  storeSeletedTags: [],
  main_category_id: '',
  rankList: []
}

function ItemList() {
  const $instance = getCurrentInstance()
  const [state, setState] = useImmer(initialState)
  const {
    keywords,
    leftList,
    rightList,
    brandSelect,
    curFilterIdx,
    filterList,
    tagList,
    curTagIdx,
    fixTop,
    routerParams,
    tabsList,
    curTabsIdx,
    storeBase,
    storeData,
    storeSeletedTags,
    main_category_id,
    rankList
  } = state
  const [isShowSearch, setIsShowSearch] = useState(false)
  const [quickList, quickListSetState] = useState([])
  const { cat_id, main_cat_id, tag_id, card_id, user_card_id } = routerParams || {}
  const { shopInfo } = useSelector((state) => state.shop)
  const dispatch = useDispatch()

  const goodsRef = useRef()
  const storeRef = useRef()
  useEffect(() => {
    // if (S.getAuthToken()) {
    //   dispatch(fetchUserFavs())
    // }
    api.item.top10List().then((res) => {
      setState((draft) => {
        draft.rankList = res
      })
    })
  }, [])

  useEffect(() => {
    // card_id, user_card_id: 兑换券参数
    entryLaunch.getRouteParams($instance.router.params).then((params) => {
      setState((draft) => {
        draft.routerParams = {
          cat_id: params.cat_id,
          main_cat_id: params.main_cat_id,
          tag_id: params.tag_id,
          card_id: params.card_id,
          user_card_id: params.user_card_id
        }
      })
    })
  }, [])
  
  useEffect( () => {
    const fetchData = async () => {
      const { list } = await api.item.getcategorynameList({ keywords: keywords })
      quickListSetState(list)
    }
    fetchData()
  }, [keywords])

  useEffect(() => {
    if (routerParams) {
      goodsRef.current.reset()
      storeRef.current.reset()
    }
  }, [routerParams])

  useEffect(() => {
    if (shopInfo && card_id) {
      goodsRef.current.reset()
    }
  }, [shopInfo])

  useDidShow(() => {
    // setTimeout(() => {
    //   if (isWeixin) {
    //     Taro.createSelectorQuery()
    //       .select('#item-list-head')
    //       .boundingClientRect((res) => {
    //         if (res) {
    //           setState((draft) => {
    //             draft.fixTop = res.bottom
    //           })
    //         }
    //       })
    //       .exec()
    //   } else {
    //     Taro.createSelectorQuery()
    //       .select('#item-list-head')
    //       .boundingClientRect((res) => {
    //         if (res) {
    //           setState((draft) => {
    //             draft.fixTop = res.bottom
    //           })
    //         }
    //       })
    //       .exec()
    //     // setState((draft) => {
    //     //   draft.fixTop = document.getElementById('item-list-head').clientHeight
    //     // })
    //   }
    // }, 1000)
  })

  const fetch = async ({ pageIndex, pageSize }) => {
    const quickListRes = await api.item.getcategorynameList({ keywords: keywords })
    quickListSetState(quickListRes.list)
    // card_id: 兑换券id
    // const { cat_id, main_cat_id, tag_id, card_id } = $instance.router.params
    let params = {
      page: pageIndex,
      pageSize,
      brand_id: brandSelect,
      keywords: keywords,
      approve_status: 'onsale,only_show',
      item_type: 'normal',
      is_point: 'false',
      tag_id,
      card_id,
      main_category_id
    }

    if (curFilterIdx == 1) {
      // 销量
      params['goodsSort'] = 1
    } else if (curFilterIdx == 2) {
      // 价格升序
      params['goodsSort'] = 3
    } else if (curFilterIdx == 3) {
      // 价格降序
      params['goodsSort'] = 2
    }

    if (curTagIdx) {
      params['tag_id'] = curTagIdx
    }

    if (cat_id) {
      params['category'] = cat_id
    }

    if (main_cat_id) {
      params['main_category'] = main_cat_id
    }

    if (VERSION_STANDARD) {
      // 有兑换券的时候，店铺ID传当前选中的店铺
      params.distributor_id = card_id ? shopInfo?.distributor_id : getDistributorId()
    }

    const { list, total_count, select_tags_list = [], brand_list } = await api.item.search(params)
    const n_list = pickBy(list, doc.goods.ITEM_LIST_GOODS)
    const resLeftList = n_list.filter((item, index) => {
      if (index % 2 == 0) {
        return item
      }
    })
    const resRightList = n_list.filter((item, index) => {
      if (index % 2 == 1) {
        return item
      }
    })

    setState((v) => {
      v.leftList[pageIndex - 1] = resLeftList
      v.rightList[pageIndex - 1] = resRightList
      v.brandList = pickBy(brand_list?.list, doc.goods.WGT_GOODS_BRAND)
      if (select_tags_list.length > 0) {
        v.tagList = [
          {
            tag_name: '全部',
            tag_id: 0
          }
        ].concat(select_tags_list)
        v.fixTop = fixTop + 34
      }
    })

    return { total: total_count }
  }

  const handleOnFocus = () => {
    setIsShowSearch(true)
  }
  const handleOnChange = (val) => {
    setState((v) => {
      v.main_category_id = ''
      v.keywords = val
    })
  }

  const handleOnClear = async () => {
    await setState((draft) => {
      draft.leftList = []
      draft.rightList = []
      draft.keywords = ''
      draft.storeData = []
    })
    setIsShowSearch(false)
    goodsRef.current.reset()
    storeRef.current.reset()
  }

  const handleSearchOff = async () => {
    setIsShowSearch(false)
    await setState((v) => {
      v.keywords = ''
    })
  }

  const handleConfirm = async (val) => {
    setIsShowSearch(false)
    await setState((draft) => {
      draft.leftList = []
      draft.rightList = []
      draft.storeData = []
      draft.keywords = val
    })
    goodsRef.current.reset()
    storeRef.current.reset()
  }

  const onChangeTag = async (index, item) => {
    await setState((draft) => {
      draft.leftList = []
      draft.rightList = []
      draft.curTagIdx = item.tag_id
    })
    goodsRef.current.reset()
  }

  const handleFilterChange = async (e) => {
    await setState((draft) => {
      draft.leftList = []
      draft.rightList = []
      draft.curFilterIdx = e.current || 0
    })
    goodsRef.current.reset()
  }

  const handleClickStore = (item) => {
    const url = `/subpages/store/index?id=${item.distributor_info.distributor_id}`
    Taro.navigateTo({
      url
    })
  }

  const onChangeTabs = (current) => {
    setState((draft) => {
      draft.curTabsIdx = current
    })
  }

  const handleStoreClick = (id, type) => {
    if (type === 'virtual_store') {
      const url = `/marketing/pages/distribution/shop-home?featuredshop=${id}`
      Taro.navigateTo({
        url
      })
    } else {
      const url = `/subpages/store/index?id=${id}`
      Taro.navigateTo({
        url
      })
    }
  }

  const handleGoodsClick = (item, shopItme) => {
    const query = {
      id: item.goodsId,
      dtid: item.distributor_id
    }
    if (shopItme.type === 'virtual_store') {
      query.dtUserId = shopItme.user_id
    }
    const url = `/pages/item/espier-detail?${qs.stringify(query)}`
    Taro.navigateTo({
      url
    })
  }

  const storeFetch = async ({ pageIndex, pageSize }) => {
    let params = {
      page: pageIndex,
      pageSize,
      keywords: keywords,
      item_type: 'normal',
      is_point: false
    }
    const { list, total, status } = await api.item.goodsItemsShop(params)

    setState((v) => {
      v.tabsList = status
        ? [
            {
              title: '商品'
            },
            {
              title: '店铺'
            }
          ]
        : [
            {
              title: '商品'
            }
          ]
      v.storeData = [...storeData, ...list]
    })
    return { total: total }
  }

  const quickClick = (e) => {
    setState((v) => {
      v.main_category_id = e
    })
    handleConfirm(keywords)
  }
  const rankClick = async (item) => {
    const { list } = await api.item.getcategorynameList({ keywords: item.category_name })
    quickClick(item.category_id)
    setState((v) => {
      v.keywords = item.category_name
    })
    quickListSetState(list)
  }
  return (
    <SpPage
      scrollToTopBtn
      className={classNames('page-item-list-category', {
        'has-tagbar': tagList.length > 0
      })}
    >
      <View className='search-wrap'>
        {/* 兑换券选择店铺 */}
        {VERSION_STANDARD && card_id && (
          <View
            className='store-picker'
            onClick={() => {
              Taro.navigateTo({
                url: '/subpages/store/list'
              })
            }}
          >
            <View className='shop-name'>{shopInfo.store_name || '暂无店铺信息'}</View>
            <Text className='iconfont icon-qianwang-01'></Text>
          </View>
        )}
        <SpSearchBar
          keyword={keywords}
          placeholder='搜索'
          quickList={quickList}
          rankList={rankList}
          quickClick={quickClick}
          rankClick={rankClick}
          onFocus={handleOnFocus}
          onChange={handleOnChange}
          onClear={handleOnClear}
          onCancel={handleSearchOff}
          onConfirm={handleConfirm}
        />
      </View>
      {quickList.length && curTabsIdx == 0 ? (
        <View className='main_category'>
          {quickList.map((item) => (
            <View
              className={classNames('main_category-item', {
                'main_category-actv': main_category_id == item.category_id
              })}
              key={item.category_id}
              onClick={() => {
                quickClick(item.category_id)
              }}
            >
              <Image
                className='main_category-item-img'
                src={item.image_url || `${process.env.APP_IMAGE_CDN}/category_null.png`}
                mode='aspectFill'
              />
              <View className='main_category-item-name'>{item.category_name}</View>
            </View>
          ))}
        </View>
      ) : (
        ''
      )}
      <AtTabs current={curTabsIdx} tabList={tabsList} onClick={onChangeTabs} swipeable={false}>
        {/* 商品 */}
        <AtTabsPane current={curTabsIdx} index={0}>
          <View className='item-list-head'>
            {tagList.length > 0 && (
              <SpTagBar
                className='tag-list'
                list={tagList}
                value={curTagIdx}
                onChange={onChangeTag}
              ></SpTagBar>
            )}
            <SpFilterBar
              custom
              current={curFilterIdx}
              list={filterList}
              onChange={handleFilterChange}
            />
          </View>
          <SpScrollView className='item-list-scroll' auto={false} ref={goodsRef} fetch={fetch}>
            <View className='goods-list'>
              <View className='left-container'>
                {leftList.map((list, idx) => {
                  return list.map((item, sidx) => (
                    <View className='goods-item-wrap' key={`goods-item-l__${idx}_${sidx}`}>
                      <SpGoodsItem
                        showFav
                        onStoreClick={handleClickStore}
                        info={{
                          ...item,
                          card_id,
                          user_card_id
                        }}
                      />
                    </View>
                  ))
                })}
              </View>
              <View className='right-container'>
                {rightList.map((list, idx) => {
                  return list.map((item, sidx) => (
                    <View className='goods-item-wrap' key={`goods-item-r__${idx}_${sidx}`}>
                      <SpGoodsItem
                        showFav
                        onStoreClick={handleClickStore}
                        info={{
                          ...item,
                          card_id,
                          user_card_id
                        }}
                      />
                    </View>
                  ))
                })}
              </View>
            </View>
          </SpScrollView>
        </AtTabsPane>
        {/* 店铺 */}
        <AtTabsPane current={curTabsIdx} index={1}>
          <SpScrollView className='item-list-scroll' auto={false} ref={storeRef} fetch={storeFetch}>
            <View className={`wgt wgt-store ${storeBase.padded ? 'wgt__padded' : null}`}>
              {storeBase.title && (
                <View className='wgt-head'>
                  <View className='wgt-hd'>
                    <Text className='wgt-title'>{storeBase.title}</Text>
                    <Text className='wgt-subtitle'>{storeBase.subtitle}</Text>
                  </View>
                </View>
              )}
              {storeData?.map((item, index) =>
                item.name ? (
                  <View
                    className='store-wrap'
                    key={'store_' + item.id + '_' + index}
                    style={{ backgroundColor: storeBase.backgroundColor || '#FFF' }}
                  >
                    <View
                      className='store-info'
                      onClick={handleStoreClick.bind(this, item.id, item.type)}
                    >
                      <Image
                        lazyLoad
                        className='store-logo'
                        src={item.logo}
                        mode='scaleToFill'
                        width={100}
                        height={100}
                      />
                      <View className='store-title'>
                        <View className='store-name'>{item.name}</View>
                        <View className='store-tags'>
                          {storeSeletedTags.length > 0 &&
                            storeSeletedTags.map((itemy) => (
                              <Text className='store-tags-item' key={itemy.tag_id}>
                                {itemy.tag_name}
                              </Text>
                            ))}
                        </View>
                      </View>
                    </View>
                    {storeBase.imgUrl && (
                      <Image lazyLoad className='store-banner' src={storeBase.imgUrl} />
                    )}
                    <ScrollView scrollX className='store-goods'>
                      {item.items.map((goods) => (
                        <View
                          className='store-goods__item'
                          onClick={handleGoodsClick.bind(this, goods, item)}
                          key={goods.goodsId}
                        >
                          <Image
                            lazyLoad
                            className='store-goods__item-thumbnail'
                            src={goods.pics}
                            mode='aspectFill'
                            width={218}
                            height={218}
                          />
                          <View
                            className='store-goods__item-price'
                            style={{ color: storeBase.borderColor }}
                          >
                            <SpPrice value={goods.price / 100} />
                          </View>
                        </View>
                      ))}
                    </ScrollView>
                  </View>
                ) : (
                  ''
                )
              )}
            </View>
          </SpScrollView>
        </AtTabsPane>
      </AtTabs>
    </SpPage>
  )
}

export default ItemList
